package handel

import (
	"828/inits"
	"828/internal/rep"
	req2 "828/internal/req"
	"828/model"
	"828/pkg"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
)

func SendSms(c *gin.Context) {
	var req req2.SendReq
	err := c.ShouldBind(&req)
	if err != nil {
		return
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(req.Mobile, strconv.Itoa(code))
	if err != nil {
		return
	}
	if *sms.Body.Code != "OK" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  *sms.Body.Message,
			"data": nil,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "发送成功",
			"data": nil,
		})
	}
	inits.Rdb.Set(inits.Ctx, "user"+req.Mobile, code, 0)
}
func Login(c *gin.Context) {
	var req req2.LoginReq
	err := c.ShouldBind(&req)
	if err != nil {
		return
	}
	var user = model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}
	inits.DB.Debug().Where("mobile = ?", user.Mobile).Find(&user)
	send, _ := inits.Rdb.Get(inits.Ctx, "user"+req.Mobile).Result()
	if send != req.SendSms {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证码错误",
			"data": nil,
		})
	}
	if user.ID == 0 {
		inits.DB.Debug().Create(&user)
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "注册成功",
			"data": user.ID,
		})
	} else {
		if user.Password != req.Password {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "密码错误",
				"data": nil,
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "已注册过此手机号,登录成功",
				"data": user.ID,
			})
		}
	}
}
func SearchSp(c *gin.Context) {
	var req req2.SearchReq
	err := c.ShouldBind(&req)
	if err != nil {
		return
	}
	var ship []model.ShiPing
	offset := (req.Page - 1) * req.Size
	inits.DB.Debug().
		Where("title like ?", "%"+req.Title+"%").
		Offset(offset).Limit(req.Size).Find(&ship)
	var b []*rep.ListRep
	for _, c := range ship {
		list := rep.ListRep{
			Title: c.Title,
			Like:  c.Like,
			Count: c.Count,
		}
		b = append(b, &list)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查找成功",
		"data": b,
	})
}
func UserFind(c *gin.Context) {
	var req req2.UserFindReq
	err := c.ShouldBind(&req)
	if err != nil {
		return
	}
	var userData model.UserData
	inits.DB.Debug().
		Where("user_id = ?", req.UserId).
		Find(&userData)
	userdatas := map[string]interface{}{
		"user_id":     userData.UserId,
		"fans":        userData.Fans,
		"follow":      userData.Follow,
		"shi_ping_id": userData.ShiPingId,
	}
	inits.Rdb.HMSet(inits.Ctx, "user"+strconv.Itoa(req.UserId), userdatas)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查找成功",
		"data": userData,
	})
}
